﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SimpleMVC.Filters
{
    public class PRGModelStateAttribute:FilterAttribute,IActionFilter
    {
        const string TEMPMODELSTATEKEY = "temp_model_state_key";
       
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            ModelStateDictionary tmpState = filterContext.Controller.TempData[TEMPMODELSTATEKEY] as ModelStateDictionary;
            if (tmpState != null)
            {
                filterContext.Controller.ViewData.ModelState.Merge(tmpState);
            }
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            if (!filterContext.Controller.ViewData.ModelState.IsValid)
            {
                if (filterContext.Result is RedirectResult)
                {
                    filterContext.Controller.TempData[TEMPMODELSTATEKEY] = filterContext.Controller.ViewData.ModelState;
                }
            }
        }
    }
}